<template>
  <div class="rules app-container">
    <div class="filter search-container" ref="search"></div>
    <el-card shadow="never">
      <template #header>
        <el-button type="primary" plain class="add-rules-btn" @click="addRules">添加巡查规则</el-button>
        <div class="red">
          <div>
            《中华人民共和国消防法》第十七条规定，消防安全重点单位除应当履行本法第十六条规定的职责外，还应当履行下列消防安全职责：（三）实行每日防火巡查，并建立巡查记录。《机关、团体、企业、事业单位消防安全管理规定》消防安全重点单位应当进行每日防火巡查，并确定巡查的人员、内容、部位和频次。公众聚集场所在营业期间的防火巡查应当至少每二小时一次；营业结束时应当对营业现场进行检查，消除遗留火种。
          </div>
        </div>
      </template>
      <el-table :height="pageHeight + 'px'" :data="rulesData" class="rule-list" v-loading="rulesDataLoading">
        <el-table-column label="规则名" prop="name"></el-table-column>
        <el-table-column label="巡检类型" prop="time_unit">
          <template #default="scope">
            <span>{{ formatTimeUnit[scope.row.time_unit] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" prop="rule_type">
          <template #default="scope">
            <span>{{ formatUnit[scope.row.rule_type] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位名" prop="unit_name"> </el-table-column>
        <!-- <el-table-column label="网格名" prop="area_name"> </el-table-column> -->
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button size="mini" @click="checkDanger(scope.$index, scope.row)">查看</el-button>
            <el-popconfirm title="您确定删除吗？" @confirm="deleteRules(scope.row)">
              <template #reference>
                <el-button type="danger" size="mini">删除</el-button>
              </template>
            </el-popconfirm>
            <!-- <el-button
              type="primary"
              size="mini"
              @click="showRulesDetail(scope.row)"
              >修改</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="rule-page">
      <el-pagination
        @current-change="handleCurrentChange"
        :total="total"
        v-model:currentPage="pagination.page"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        background
      >
      </el-pagination>
    </div>
    <el-dialog
      v-model="addRuleVisible"
      width="50%"
      @close="closeDialog"
      @opened="openDialog"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form ref="addRuleForm" :model="formData" label-position="right">
        <el-row>
          <el-col>
            <el-form-item label="规则名称" prop="name">
              <el-input v-model="formData.name" class="rule-name-ipt"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="巡检类型" prop="time_unit">
              <el-select v-model="formData.time_unit" placeholder="请选择">
                <el-option v-for="item in ruleTimeList" :key="item.key" :label="item.label" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="前置有效时间">
              <el-input placeholder="请输入（以小时为单位）" v-model="formData.pre_validity">
                <template #append>
                  <span style="color: #000">时</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="4">
            <el-form-item label="后置有效时间">
              <el-input placeholder="请输入（以小时为单位）" v-model="formData.after_validity">
                <template #append>
                  <span style="color: #000">时</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="规则时间">
              <el-time-picker v-model="choosedTime" placeholder="请选择" is-range format="HH:mm" value-format="HH:mm">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="不检日期">
              <el-select v-model="formData.not_check_date" multiple style="margin-left: 20px" placeholder="请选择">
                <el-option v-for="item in noDateList" :key="item.key" :label="item.label" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="任务对象（本单位、子商户）" prop="rule_type">
              <el-select v-model="formData.rule_type" placeholder="请选择" @change="pickRuleType">
                <el-option v-for="item in ruleTypeMap" :key="item.name" :label="item.name" :value="item.value">
                </el-option>
              </el-select>
              <el-select
                v-model="formData.sub_unit_id"
                placeholder="请选择"
                @change="selectRuleType"
                v-if="formData.rule_type == 'sub_unit'"
              >
                <el-option v-for="item in ruleTypeoptions" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="巡查人员">
              <el-select v-model="formData.users" multiple style="margin-left: 20px" placeholder="请选择">
                <el-option v-for="item in patrolUserList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="选择巡查点">
              <div style="border: 1px solid #dde4ed; padding: 10px; width: 100%">
                <el-select v-model="isImportant" placeholder="请选择类型" @change="isImportantChange">
                  <el-option v-for="item in isImportantList" :key="item.key" :label="item.label" :value="item.key">
                  </el-option>
                </el-select>
                <el-table
                  ref="multipleTable"
                  :data="tableData"
                  tooltip-effect="dark"
                  height="30vh"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" width="55"> </el-table-column>
                  <el-table-column label="ID" width="80" prop="id"></el-table-column>
                  <el-table-column prop="name" label="名称"> </el-table-column>
                  <el-table-column prop="address" label="位置"></el-table-column>
                </el-table>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="btns">
        <el-button @click="addRuleVisible = false">取消</el-button>
        <el-button type="primary" class="btn" @click="addSub">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="pointLogDialog" width="50%" destroy-on-close :title="ruleDetails.name">
      <el-descriptions :column="1" size="Large" border>
        <el-descriptions-item label="单位名称">{{ ruleDetails.unit_name }}</el-descriptions-item>
        <el-descriptions-item label="单位地点">
          {{ ruleDetails.unit_address }}
        </el-descriptions-item>
        <el-descriptions-item label="巡查规则">{{ ruleDetails.name }}</el-descriptions-item>
        <!-- <el-descriptions-item label="规则添加时间" :span="2">{{  ruleDetails.add_time}}</el-descriptions-item> -->
        <el-descriptions-item label="巡查开始时间">{{ ruleDetails.start_time }} </el-descriptions-item>
        <el-descriptions-item label="巡查结束时间">{{ ruleDetails.end_time }} </el-descriptions-item>
        <el-descriptions-item label="执行日期">{{ $getDateTime(ruleDetails.date) }} </el-descriptions-item>
        <el-descriptions-item label="添加时间">{{ $getDateTime(ruleDetails.add_time) }} </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ $getDateTime(ruleDetails.release_time) }} </el-descriptions-item>
        <el-descriptions-item label="下次执行时间">{{ $getDateTime(ruleDetails.next_time) }} </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import paginationMixin from '@/mixins/pagination'
import { resolve } from 'tinymce/themes/silver/theme'
export default {
  mixins: [paginationMixin],
  data() {
    return {
      addRuleVisible: false,
      rulesInfo: {},
      rulesData: [],
      rulesDataLoading: false,
      ruleTimeList: [
        { label: '天', key: 1 },
        { label: '周', key: 2 },
        { label: '月', key: 3 },
        { label: '季', key: 4 },
        { label: '年', key: 5 },
        { label: '2小时', key: 6 }
      ],
      ruleTypeMap: [
        {
          name: '本单位',
          value: 'unit'
        },
        {
          name: '子商户',
          value: 'sub_unit'
        }
      ],
      typeCascaderProps: {
        label: 'name',
        value: 'id',
        children: 'sub_item',
        leaf: 'children'
      },
      total: 0,
      ruleTypeoptions: [],
      ruleTypePicked: '',
      formatTimeUnit: {
        1: '天',
        2: '周',
        3: '月',
        4: '季',
        5: '年',
        6: '2小时'
      },
      formatUnit: {
        unit: '社会单位',
        sub_unit: '社会单位商户'
      },
      noDateList: [
        { label: '周一', key: '1' },
        { label: '周二', key: '2' },
        { label: '周三', key: '3' },
        { label: '周四', key: '4' },
        { label: '周五', key: '5' },
        { label: '周六', key: '6' },
        { label: '周日', key: '7' }
      ],
      tableData: [],
      tableDataInfo: '',
      pointLogDialog: false,
      patrolUserList: [],
      isImportantList: [
        { label: '全部', key: '' },
        { label: '重点巡查点', key: 1 },
        { label: '普通巡查点', key: 0 }
      ],
      isImportant: '',
      choosedTime: '', //规则时间（提交时处理为start_time与end_time)
      formData: {
        name: '',
        pre_validity: '', //前置有效时间
        after_validity: '', //后置有效时间
        not_check_date: '', //不检日期
        points: '', //点位编号
        users: '', //巡查人编号
        sub_unit_id: '', //商户编号
        no_sub: '', //是否为商户
        time_unit: '', //巡检类型
        rule_type: '' //单位类型
      },
      ruleId: '',
      ruleDetails: {},
      pageHeight: 0
    }
  },
  created() {
    this.initRuleList()
  },
  mounted() {
    this.pageHeight = window.innerHeight - 350
  },
  methods: {
    checkDanger(index, row) {
      console.log(row)
      this.ruleDetails = row
      this.pointLogDialog = true
    },
    async showRulesDetail(row) {
      this.ruleId = row.id
      this.choosedTime = [row.start_time, row.end_time]
      let formData = this.formData
      for (let key in formData) {
        try {
          let val = JSON.parse(row[key])
          if (key == 'users') {
            let temp = val.map(Number)
            formData[key] = temp
          } else {
            formData[key] = val
          }
        } catch {
          formData[key] = row[key]
        }
      }
      if (row.rule_type == 'sub_unit') {
        this.formData.no_sub = 0
        this.getSubUnitLists(row.rule_type)
        await this.getUserList()
        await this.getPointList()
      } else {
        this.formData.no_sub = 1
        await this.getUserList()
        await this.getPointList()
      }
      this.$nextTick(() => {
        this.addRuleVisible = true
      })
    },
    openDialog() {
      let rows = []
      let tempData = this.tableData
      let point = this.formData.points
      point.map((curVal) => {
        tempData.map((val) => {
          if (curVal == val.id) rows.push(val)
        })
      })
      rows.map((row) => {
        this.$refs.multipleTable.toggleRowSelection(row)
      })
    },
    closeDialog() {
      this.$refs.addRuleForm.resetFields()
      this.isImportant = ''
      this.ruleId = ''
      this.choosedTime = ''
      this.tableData = []
      this.patrolUserList = []
      this.$refs.multipleTable.clearSelection()
      for (let item in this.formData) {
        this.formData[item] = ''
      }
    },
    deleteRules(row) {
      this.$api.post('/unit/PatrolRule/delete', { id: row.id }).then((res) => {
        this.initRuleList()
        this.$message.success('删除成功')
      })
    },
    isImportantChange() {
      this.getPointList()
    },
    handleSelectionChange(e) {
      let temp = []
      e.map((curVal) => {
        temp.push(curVal.id)
      })
      this.formData.points = temp
    },
    getPointList() {
      return new Promise((resolve) => {
        this.$api
          .post('/unit/PatrolPosition/all', {
            sub_unit_id: this.formData.sub_unit_id,
            is_key: this.isImportant
          })
          .then((res) => {
            this.tableData = res.data
            resolve()
          })
          .catch((err) => {
            resolve()
          })
      })
    },
    selectRuleType() {
      this.getUserList()
      this.getPointList()
      this.isImportant = ''
      this.formData.users = []
    },
    pickRuleType(e) {
      this.formData.sub_unit_id = ''
      this.formData.no_sub = ''
      this.formData.users = ''
      this.formData.points = ''
      this.tableData = []
      this.patrolUserList = []
      this.isImportant = ''
      this.$refs.multipleTable.clearSelection()
      if (e == 'sub_unit') {
        this.formData.no_sub = 0
        this.getSubUnitLists(e)
      } else {
        this.formData.no_sub = 1
        this.getUserList()
        this.getPointList()
      }
    },
    getUserList() {
      return new Promise((resolve) => {
        this.$api
          .post('/unit/UnitContacts/all', {
            sub_unit_id: this.formData.sub_unit_id,
            not_admin: 1
          })
          .then((res) => {
            this.patrolUserList = res.data
            resolve()
          })
          .catch((err) => {
            resolve()
          })
      })
    },
    getSubUnitLists(watchLevel) {
      //获取社会单位
      this.$api.post('/unit/YjUnit/SubUnitLists', { rows: 100 }).then((res) => {
        this.ruleTypeoptions = res.data.list
      })
    },
    addRules() {
      this.addRuleVisible = true
      for (let item in this.formData) {
        this.formData[item] = ''
      }
    },
    initRuleList() {
      this.rulesDataLoading = true
      this.$api
        .post('/unit/PatrolRule/lists', {
          rows: this.pagination.size,
          page: this.pagination.page
        })
        .then((res) => {
          this.rulesData = res.data.lists
          this.total = res.data.total
        })
        .finally(() => {
          this.rulesDataLoading = false
        })
    },
    handleCurrentChange() {
      this.initRuleList()
    },
    addSub() {
      let tempTime = this.choosedTime
      let temp = this.formData
      this.ruleId ? (temp.id = this.ruleId) : ''
      temp.start_time = tempTime[0]
      temp.end_time = tempTime[1]
      this.$api.post('/unit/PatrolRule/save', temp).then((res) => {
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.addRuleVisible = false
        this.initRuleList()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.red {
  color: red;
  font-size: 14px;
  margin-top: 15px;
}

.rule-list {
  margin-top: 50px;
}
.rule-page {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.btns {
  display: flex;
  justify-content: space-around;
  width: 200px;
  margin: 30px auto 0;
}
.rule-name-ipt {
  width: 220px;
}
.block {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}
</style>
